import { API_CONFIG } from '../config/constants';
import { generateSessionId } from '../utils/helpers';

export class ChatService {
    static async stopGeneration(sessionId) {
        try {
            console.log('🛑 停止AI生成:', sessionId);
            
            const response = await fetch(`${API_CONFIG.CHAT_CLOSE_URL}?sessionId=${sessionId}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            if (!response.ok) {
                throw new Error('停止生成失败');
            }

            console.log('✅ AI生成已停止');
            return true;
        } catch (error) {
            console.error('停止生成失败:', error);
            throw error;
        }
    }

    static async sendMessage(query, sessionId) {
        // 如果没有提供sessionId，生成一个临时的
        const finalSessionId = sessionId || generateSessionId();
        
        const response = await fetch(API_CONFIG.CHAT_STREAM_URL, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'text/event-stream',
            },
            body: JSON.stringify({
                session_id: finalSessionId,
                interrupt_feedback: "",
                query: query,
                type: "node_object"
            })
        });

        if (!response.ok) {
            throw new Error('网络请求失败');
        }

        return response;
    }

    static async *processStreamResponse(response) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        try {
            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = lines.pop() || '';

        for (const line of lines) {
          const trimmedLine = line.trim();
          if (trimmedLine && trimmedLine.startsWith('data:')) {
            try {
              const jsonStr = trimmedLine.substring(5).trim();
              if (jsonStr && jsonStr !== '[DONE]') {
                const data = JSON.parse(jsonStr);
                if (data.data && Array.isArray(data.data)) {
                  yield data.data;
                }
              }
            } catch (e) {
              console.error('解析JSON失败:', e);
            }
          }
        }
      }
    } finally {
      reader.releaseLock();
    }
  }

  static async getHistory({ sessionId, pageSize = 10, lastCreateTime = '' }) {
    const requestBody = { sessionId, pageSize, lastCreateTime };
    
    console.log('历史记录API请求:', requestBody);
    
    const response = await fetch(API_CONFIG.CHAT_HISTORY_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(requestBody)
    });

    if (!response.ok) {
      throw new Error('获取历史消息失败');
    }

    const result = await response.json();
    console.log('历史记录API响应:', result);
    
    if (result && result.code === 0 && result.data && Array.isArray(result.data.records)) {
      return result.data;
    }
    return { records: [], total: 0, size: pageSize, current: 1, pages: 0 };
  }
}